package com.deng.api.config;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 七牛云
 */
@Component
public class QiNiuUtil {

    @Autowired
    private QiNiuConfig qiNiuConfig;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String upload(MultipartFile file){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = qiNiuConfig.getAccessKey();
        String secretKey = qiNiuConfig.getSecretKey();
        String bucket = qiNiuConfig.getBucket();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = getFileName(file.getOriginalFilename())+"-"+System.currentTimeMillis()
                +"."+getExc(file.getOriginalFilename());
        try {
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte [] bs = new byte[1024];
            int len = -1;
            while ( (len = inputStream.read(bs)) != -1){
                out.write(bs,0,len);
            }
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(out.toByteArray(),key,upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
                System.err.println(putRet.key);
                System.err.println(putRet.hash);
                return qiNiuConfig.getDomainOfBucket()+"/" +putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取文件名
     * @param file
     * @return
     */
    public String getFileName(String file){
        if (file == null || file.length() ==0){
            return "";
        }
        int i = file.lastIndexOf(".");
        if (i != -1 && i<file.length()){
            return file.substring(0,i);
        }
        return "";
    }

    /**
     * 获取格式名
     * @param file
     * @return
     */
    public String getExc(String file){
        if (file == null || file.length() ==0){
            return "";
        }
        int i = file.lastIndexOf(".");
        if (i != -1 && i<file.length()){
            return file.substring(i+1);
        }
        return "";
    }

}
